import { _decorator, sys, Node, Sprite, Button, Label, Material, view, Vec3, UITransform, UIOpacity, Vec2, UIRenderer, Graphics, color, find, Mat4, Rect } from 'cc';
import ResManager from '../manager/ResManager';
const { ccclass, property } = _decorator;
export default class CCApi {
  public static async setNodeGray(node: Node, bool: boolean) {
    node.children.forEach((child) => CCApi.setNodeGray(child, bool));
    let uiRenderer = node.getComponent(UIRenderer);
    if (!uiRenderer) return;
    let materialName = bool ? 'ui-sprite-gray-material' : 'ui-sprite-material';
    let material = await ResManager.Ins.load<Material>(`home/materials/${materialName}`);
    uiRenderer.customMaterial = material;
  }

  public static isLongScreenMachine() {
    let winSize = view.getVisibleSize();
    return winSize.height / winSize.width > 2.1;
    console.log('--当前游戏窗口大小  w:' + winSize.width + '   h:' + winSize.height);

    let viewSize = view.getFrameSize();
    console.log('--视图边框尺寸：w:' + viewSize.width + '  h:' + viewSize.height);

    let canvasSize = view.getCanvasSize(); //视图中canvas尺寸
    console.log('--视图中canvas尺寸  w:' + canvasSize.width + '  H:' + canvasSize.height);

    let visibleSize = view.getVisibleSize();
    console.log('--视图中窗口可见区域的尺寸 w:' + visibleSize.width + '   h:' + visibleSize.height);

    let designSize = view.getDesignResolutionSize();
    console.log('--设计分辨率：' + designSize.width + '    h: ' + designSize.height);
  }

  public static getCanvasPosition(target: Node, parentName = 'Canvas', position?: Vec3) {
    if (!position && target && target.position) position = target.position.clone();
    if (!position) return null;
    if (target.parent && target.parent.name != parentName && target.parent.position) {
      position.x += target.parent.position.x;
      position.y += target.parent.position.y;
      target = target.parent;
      this.getCanvasPosition(target, parentName, position);
    }
    return position;
  }

  public static isOnPc(): boolean {
    return sys.platform == sys.Platform.DESKTOP_BROWSER;
  }

  public static isOnBrowser(): boolean {
    return sys.platform == sys.Platform.DESKTOP_BROWSER || sys.platform == sys.Platform.MOBILE_BROWSER;
  }

  public static isShowDebug(): boolean {
    if (sys.platform === sys.Platform.MOBILE_BROWSER || sys.platform === sys.Platform.DESKTOP_BROWSER) {
      if (window.location.protocol === 'http:') {
        // 对应直接用电脑cocos运行的情况
        return true;
      } else {
        // 用https网址访问cdn中的web工程的情况
        // 在网址后面加上?showDebug=true来显示GM按钮
        let usp = new URLSearchParams(window.location.search);
        return !!usp.get('showDebug');
      }
    }
    return false;
  }

  public static isHTTPs(): boolean {
    return this.isOnBrowser() && window.location.protocol === 'https:';
  }

  public static isOnWechat() {
    return sys.platform == sys.Platform.WECHAT_GAME && !window['ks'];
  }

  public static isOnByte() {
    return sys.platform == sys.Platform.BYTEDANCE_MINI_GAME;
  }

  public static isOnVivo() {
    return sys.platform == sys.Platform.VIVO_MINI_GAME;
  }

  public static isOnAndroid() {
    return sys.os == sys.OS.ANDROID && sys.isNative;
  }

  public static v3v2(vec3: Vec3): Vec2 {
    return new Vec2(vec3.x, vec3.y);
  }

  public static v2v3(vec2: Vec2): Vec3 {
    return new Vec3(vec2.x, vec2.y, 0);
  }

  private static showBoundingBoxGraphicsTimeout: NodeJS.Timeout = null;
  public static showBoundingBoxGraphics(node: Node) {
    let graphicsNode = find('Canvas/graphicsNode');
    if (!graphicsNode) {
      graphicsNode = new Node('graphicsNode');
      graphicsNode.parent = find('Canvas');
      graphicsNode.addComponent(Graphics);
    }
    const graphics = graphicsNode.getComponent(Graphics);
    // graphics.clear();

    // 获取节点的包围盒（在节点本地坐标系中）
    let rect = this.getBoundingBox(node);
    // 获取节点的世界变换矩阵
    let worldMatrix = node.getWorldMatrix();
    // 将节点的本地包围盒转换为世界坐标系中的包围盒
    let rectWorld = rect.transformMat4(worldMatrix);
    // 获取节点的世界变换矩阵
    let worldMatrix2 = graphicsNode.getWorldMatrix();
    // 计算节点的世界变换矩阵的逆矩阵（本地坐标系转世界坐标系的逆变换）
    let inverseWorldMatrix = new Mat4();
    Mat4.invert(inverseWorldMatrix, worldMatrix2);
    // 将节点在世界坐标系中的包围盒转换为节点本地坐标系中的包围盒
    let rectLocal = rectWorld.transformMat4(inverseWorldMatrix);

    graphics.rect(rectLocal.x, rectLocal.y, rectLocal.width, rectLocal.height);
    let random1 = Math.floor(Math.random() * 256);
    let random2 = Math.floor(Math.random() * 256);
    let random3 = Math.floor(Math.random() * 256);
    graphics.fillColor = color(random1, random2, random3, 150);
    graphics.fill();

    clearTimeout(this.showBoundingBoxGraphicsTimeout);
    this.showBoundingBoxGraphicsTimeout = setTimeout(() => {
      graphicsNode.destroy();
    }, 2000);
  }

  public static getBoundingBox(node: Node): Rect {
    let { anchorPoint, contentSize } = node.getComponent(UITransform);
    let { width, height } = contentSize;
    let rect = new Rect(-anchorPoint.x * width, -anchorPoint.y * height, width, height);
    return rect;
  }
}
